package com.systemframework.sys.controller;

import cn.dev33.satoken.SaManager;
import cn.dev33.satoken.stp.SaLoginModel;
import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.systemframework.annotation.LicenseAnnotation;
import com.systemframework.annotation.LogAnnotation;
import com.systemframework.constants.Constants;
import com.systemframework.sys.dto.request.LoginRequestDTO;
import com.systemframework.sys.dto.response.SysMenuResponseDTO;
import com.systemframework.sys.dto.response.SysUserResponseDTO;
import com.systemframework.sys.service.SysMenuService;
import com.systemframework.sys.service.SysUserService;
import com.systemframework.util.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @author summer
 * @date 2023-02-15 14:56
 */
@RestController
@Slf4j
public class LoginController {


    private SysUserService sysUserService;

    @Autowired
    public void setSysUserService(SysUserService sysUserService) {
        this.sysUserService = sysUserService;
    }

    @LicenseAnnotation
    @LogAnnotation(msg = "登录")
    @PostMapping(value = "/login")
    public Result<SaTokenInfo> login(@RequestBody LoginRequestDTO loginRequestDTO){
        SysUserResponseDTO sysUserResponseDTO=sysUserService.login(loginRequestDTO);
        SaLoginModel saLoginModel = SaLoginModel.create().setIsLastingCookie(loginRequestDTO.getIsRemember())
                .setDevice(Constants.DEVICE_LOGIN);
        StpUtil.login(sysUserResponseDTO.getId(),saLoginModel);
        SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
        if(StrUtil.isNotEmpty(SaManager.getConfig().getTokenPrefix())){
            tokenInfo.setTokenValue(SaManager.getConfig().getTokenPrefix()+" "+tokenInfo.getTokenValue());
        }
        return Result.successResult(tokenInfo);
    }

    private SysMenuService sysMenuService;

    @Autowired
    public void setSysMenuService(SysMenuService sysMenuService) {
        this.sysMenuService = sysMenuService;
    }

    @GetMapping(value = "/index")
    @LicenseAnnotation
    public Result<List<SysMenuResponseDTO>> index(){
        List<SysMenuResponseDTO> sysMenuResponseDTOList= sysMenuService.findUserAndMenuLists(StpUtil.getLoginIdAsInt());
        return Result.successResult(sysMenuResponseDTOList);
    }

    @LogAnnotation(msg = "退出")
    @PostMapping(value = "/logout")
    public Result<String> logout(){
        StpUtil.logout();
        return Result.successResult();
    }
}
